import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    name: 'Layout',
    component:() => import('../layout/Layout.vue'),
    redirect: "/home",
    children: [
      {
        path:'home',
        name:'Home',
        component: () => import('../views/HomeView.vue'),
      },
      {
          path: 'personCenter',   //  路由 -> //personCenter  不对
          name: 'PersonCenter',
          component: () => import('../views/PerSonCenter.vue')
      },
    ]
  },





  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/404.vue')
  },
  {
    path: '/:pathMatch(.*)',  // 匹配所有未知路由
    redirect: '/404'    // 重定向到404页面
  },
  

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})



// 路由守卫
router.beforeEach((to, from, next) => {

  // 这里坑比较多 千万要注意
  const user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")).loginData.user  : false
  const noPermissionPaths = ['/login', '/register']   // 定义无需登录的路由
  if (!user && !noPermissionPaths.includes(to.path)) {  // 用户没登录,  假如你当前跳转login页面，然后login页面没有用户信息，这个时候你再去往 login页面跳转，就会发生无限循环跳转
    // 获取缓存的用户数据
      //  如果to.path === '/login' 的时候   !noPermissionPaths.includes(to.path) 是返回 false的，也就不会进 next("/login")
    next("/login")
  } else {
    next()
  }
})


export default router
